package com.mo.tools.sequence;

import com.mo.tools.sequence.service.impl.SequenceServiceImpl;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.stereotype.Component;

import java.util.concurrent.atomic.AtomicLong;

/**
 * @name: SequenceGeneratorBean
 * @description:
 * @author: Yang Xingfu
 * @date: 2019-12-18 18:15
 **/
//@Component
@Slf4j
public class SequenceGeneratorBean {

    /**
     * 机器信息对象
     */
    @Autowired
    private MachineProperties machineProperties;

    /**
     * sequence序列处理对象
     */
    @Autowired
    private SequenceServiceImpl sequenceService;


    public static final String TEST_SEQUENCE_NAME = "file_sequence:";

    public static final String TEST_SEQUENCE_PREFIX = "FU";

    public static final int TEST_SEQUENCE_LENGTH = 6;

    @Bean("fileSequenceGenerator")
    SequenceGenerator fileSequenceGenerator() {
        FileSequence sequence = null;
        SequenceGenerator sequenceGenerator = null;
        try {

            sequence = new FileSequence(TEST_SEQUENCE_NAME + TEST_SEQUENCE_PREFIX, TEST_SEQUENCE_LENGTH, TEST_SEQUENCE_PREFIX);
            sequence = sequenceService.initializeFind(sequence);

            if (sequence == null) {
                throw new Exception("序列初始化失败");
            }


            AtomicLong initializeSequence = new AtomicLong(Long.valueOf(sequence.getSequence()));

            ISequenceCallBack callBack = createCallBack(sequence);
            sequenceGenerator = new SequenceGenerator(
                    machineProperties.getNumber(),
                    machineProperties.getServiceNumber(),
                    TEST_SEQUENCE_LENGTH,
                    TEST_SEQUENCE_PREFIX,
                    initializeSequence, callBack);
        } catch (Exception e) {
            log.error("序列初始化失败");
            e.printStackTrace();
        }
        return sequenceGenerator;
    }

    public ISequenceCallBack createCallBack(FileSequence sequence) {
        return new ISequenceCallBack() {
            @Override
            public void execute(SequenceGenerator sequenceGenerator) {
                sequence.setCode(sequenceGenerator.code);
                sequence.setSequence(sequenceGenerator.sequence);
                sequenceService.update(sequence);

            }
        };
    }


}
